// utils/webpush.js

//公钥
const VAPID_PUBLIC_KEY =
	'BJxx74rV5ojMZs7H43pKANSA1qQpzthr-0s32JFURtgeUkrV5evVXkr8wq5LZwRE_6fhOQSyjd1MMxutE6puu0Y';

// --- 工具方法 ---
function urlBase64ToUint8Array(base64String) {
	const padding = '='.repeat((4 - base64String.length % 4) % 4);
	const base64 = (base64String + padding)
		.replace(/\-/g, '+')
		.replace(/_/g, '/');
	const rawData = window.atob(base64);
	const outputArray = new Uint8Array(rawData.length);
	for (let i = 0; i < rawData.length; ++i) {
		outputArray[i] = rawData.charCodeAt(i);
	}
	return outputArray;
}

// --- 平台信息 ---
function getPlatformInfo() {
	const userAgent = navigator.userAgent.toLowerCase();
	const platform = navigator.platform.toLowerCase();
	if (platform.includes('win')) return 'windows';
	if (platform.includes('mac')) return 'macos';
	if (platform.includes('iphone') || platform.includes('ipad')) return 'ios';
	if (userAgent.includes('android')) return 'android';
	return 'web';
}

// --- 将订阅信息保存到服务器 ---
async function sendSubscriptionToServer(subscription, account = 0) {
	try {
		const platform = getPlatformInfo();
		await fetch('https://cloud.mfarmers.com/api-push/save-subscription', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				subscription,
				account,
				platform
			})
		});
		console.log('✅ 推送订阅已保存到服务器');
	} catch (err) {
		console.error('❌ 保存推送订阅失败:', err);
	}
}

// --- 订阅推送 ---
async function subscribeToPush(registration, account = 0) {
	if (!('PushManager' in window)) {
		console.warn('当前浏览器不支持推送');
		return null;
	}

	const permission = await Notification.requestPermission();
	if (permission !== 'granted') {
		console.warn('用户拒绝推送权限');
		return null;
	}

	let subscription = await registration.pushManager.getSubscription();

	if (!subscription) {
		const convertedVapidKey = urlBase64ToUint8Array(VAPID_PUBLIC_KEY);
		subscription = await registration.pushManager.subscribe({
			userVisibleOnly: true,
			applicationServerKey: convertedVapidKey
		});

		if (!subscription.endpoint) throw new Error('订阅失败：缺少 endpoint');
		await sendSubscriptionToServer(subscription, account);
	} else {
		console.log('已存在订阅:', subscription.endpoint);
	}

	return subscription;
}

// --- 处理 WebSocket 消息显示通知 ---
function setupWebSocketNotification(registration) {
	uni.$on('websocketMessage', (message) => {
		if (message.type === 'chatMessage' && document.hidden) {
			console.log('收到WebSocket消息，转发给Service Worker:', message);
			if (registration.active) {
				registration.active.postMessage({
					type: 'SHOW_CHAT_NOTIFICATION',
					data: {
						title: message.data?.from?.name || '新消息',
						body: message.data?.content || '您收到一条新消息',
						icon: '/static/logo.png',
						badge: '/static/logo.png',
						conversation_id: message.data?.to?.account || '',
						message_data: message.data
					}
				});
			} else {
				console.warn('Service Worker 未激活');
			}
		}
	});
}

// --- 外部可直接调用的方法 ---
export async function initPushAndNotification(account = 0) {
	if (!('serviceWorker' in navigator)) {
		console.warn('当前环境不支持 Service Worker');
		return;
	}

	// 等待 Service Worker 就绪（确保已在 App.vue 注册）
	const registration = await navigator.serviceWorker.ready;
	console.log('Service Worker 已就绪');

	// 订阅推送
	await subscribeToPush(registration, account);

	// 建立 WebSocket 通知转发
	setupWebSocketNotification(registration);
}